/**
 * 响应完整的页面信息
 */

const http = require('http');
const path = require('path');
const fs = require('fs');
const mime = require('./mime.json');

console.log(mime['.txt']);

http.createServer((req, resp) => {
    fs.readFile(path.join(__dirname, 'www', req.url),(err, fileContent)=>{
        if (err) {
            resp.writeHead(404, {
                'Content-Type': 'text/plain; charset=utf8'
            });
            resp.end('资源不存在！');
        } else {
            let ext = path.extname(req.url);
            let defaultType = 'text/html';
            if (mime[ext]) {
                defaultType = mime[ext];
            }
            if (defaultType.startsWith('text')) {
                defaultType += '; charset=utf8';
            }
            resp.writeHead(200, {
                'Content-Type': defaultType
            });
            resp.end(fileContent);
        }
    });
}).listen(3000, ()=>{
    console.log('running...');
});

